<template>
  <div class="notification-dropdown">
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
      <el-dropdown trigger="click" @command="handleCommand" placement="bottom-end">
        <el-button :icon="Bell" circle class="notification-button" />
        <template #dropdown>
          <el-dropdown-menu class="notification-menu">
            <div class="notification-header">
              <span class="notification-title">通知</span>
              <el-button
                v-if="unreadCount > 0"
                type="text"
                size="small"
                @click="handleMarkAllRead"
              >
                全部已读
              </el-button>
            </div>
            <el-scrollbar max-height="400px">
              <div v-if="loading" class="notification-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>加载中...</span>
              </div>
              <div v-else-if="notifications.length === 0" class="notification-empty">
                <el-empty description="暂无通知" :image-size="80" />
              </div>
              <div v-else class="notification-list">
                <div
                  v-for="notification in notifications"
                  :key="notification.id"
                  class="notification-item"
                  :class="{ 'is-unread': !notification.is_read }"
                  @click="handleNotificationClick(notification)"
                >
                  <div class="notification-content">
                    <div class="notification-title-text">{{ notification.title }}</div>
                    <div class="notification-body">{{ notification.content }}</div>
                    <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
                  </div>
                  <div class="notification-actions">
                    <el-button
                      v-if="!notification.is_read"
                      type="text"
                      size="small"
                      :icon="Check"
                      @click.stop="handleMarkRead(notification.id)"
                    />
                    <el-button
                      type="text"
                      size="small"
                      :icon="Delete"
                      @click.stop="handleDelete(notification.id)"
                    />
                  </div>
                </div>
              </div>
            </el-scrollbar>
            <div class="notification-footer">
              <el-button type="text" @click="handleViewAll">查看全部</el-button>
            </div>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-badge>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Bell, Loading, Check, Delete } from '@element-plus/icons-vue'
import { useNotificationStore } from '@/stores/notification'
import type { Notification } from '@/types/notification'
import { RelatedObjectType } from '@/types/notification'

const router = useRouter()
const route = useRoute()
const notificationStore = useNotificationStore()

const notifications = computed(() => notificationStore.notifications.slice(0, 10)) // 只显示最近10条
const unreadCount = computed(() => notificationStore.unreadCount)
const loading = computed(() => notificationStore.loading)

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  return date.toLocaleDateString()
}

// 处理下拉菜单命令
const handleCommand = (_command: string) => {
  // 可以在这里处理其他命令
}

// 处理通知点击
const handleNotificationClick = async (notification: Notification) => {
  // 如果未读，标记为已读
  if (!notification.is_read) {
    await handleMarkRead(notification.id)
  }

  // 跳转到相关页面
  if (notification.related_type && notification.related_id) {
    if (notification.related_type === RelatedObjectType.TASK) {
      router.push(`/tasks/${notification.related_id}`)
    } else if (notification.related_type === RelatedObjectType.PROJECT) {
      router.push(`/projects/${notification.related_id}`)
    }
  }
}

// 标记为已读
const handleMarkRead = async (notificationId: string) => {
  try {
    await notificationStore.markAsRead(notificationId)
  } catch (error) {
    ElMessage.error('标记已读失败')
  }
}

// 标记全部为已读
const handleMarkAllRead = async () => {
  try {
    await notificationStore.markAllAsRead()
    ElMessage.success('已标记全部为已读')
  } catch (error) {
    ElMessage.error('标记全部已读失败')
  }
}

// 删除通知
const handleDelete = async (notificationId: string) => {
  try {
    await notificationStore.removeNotification(notificationId)
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 查看全部
const handleViewAll = () => {
  router.push('/notifications')
}

// 组件挂载时加载通知并开始轮询
onMounted(async () => {
  // 如果当前在通知页面，不在这里加载通知，让通知页面自己加载
  if (route.path === '/notifications') {
    notificationStore.connectStream()
    return
  }
  
  // 如果通知列表为空，才加载通知
  if (notificationStore.notifications.length === 0) {
    await notificationStore.fetchNotifications({ limit: 10 })
  }
  // 连接 SSE 实时推送
  notificationStore.connectStream()
})

// 组件卸载时断开连接
onUnmounted(() => {
  notificationStore.disconnectStream()
})
</script>

<style scoped lang="scss">
.notification-dropdown {
  .notification-button {
    border: none;
    background: transparent;
  }
}

.notification-menu {
  width: 360px;
  padding: 0;

  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);

    .notification-title {
      font-weight: 600;
      font-size: 16px;
    }
  }

  .notification-loading,
  .notification-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: var(--el-text-color-secondary);
  }

  .notification-list {
    .notification-item {
      display: flex;
      padding: 12px 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background-color: var(--el-fill-color-light);
      }

      &.is-unread {
        background-color: var(--el-color-primary-light-9);

        .notification-title-text {
          font-weight: 600;
        }
      }

      .notification-content {
        flex: 1;
        min-width: 0;

        .notification-title-text {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .notification-body {
          font-size: 12px;
          color: var(--el-text-color-regular);
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .notification-time {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }

      .notification-actions {
        display: flex;
        flex-direction: column;
        gap: 4px;
        margin-left: 8px;
      }
    }
  }

  .notification-footer {
    padding: 8px 16px;
    text-align: center;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}
</style>

